<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="searchWrap">
        <div class="searchBox"><span>计划状态：</span>
          <div @click="selectAll('activeNum')"
               class="searchItem"
               :class="activeNum==='' ? 'active':''">全部
          </div>
          <div @click="searchByStatusVersion(item.code,index)" class="searchItem"
               :class="activeNum === index ? 'active':''" v-for="(item,index) in statusList"
               :key="item.code">{{ item.text }}
          </div>
        </div>

      </div>
    </el-card>
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form :model="where" class="ele-form-search" label-width="77px" @keyup.enter.native="reload"
               @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="计划信息:">
              <el-input v-model="where.keyword" clearable placeholder="请输入计划信息  "/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="日期范围:">
              <el-date-picker
                style="width: 100%;"
                v-model="date"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button v-if="permission.includes('sys:plan:index')" class="ele-btn-icon" icon="el-icon-search"
                         type="primary" @click="reload">
                查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table ref="table" :columns="columns" :datasource="url" :selection.sync="selection" :where="where"
                     height="calc(100vh - 405px)">
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <div class="btnWrap">
            <el-button icon="el-icon-plus" size="small" type="primary" @click="addPlan"
                       v-show="permission.includes('sys:plan:add')">
              添加
            </el-button>
          </div>
          <div class="btnWrap" v-if="permission.includes('sys:plan:export')">
            <el-button size="small" type="primary" @click="exportPart" :loading="exportLoading"
                       :disabled="!selection.length&&!exportFlag">
              导出
            </el-button>
          </div>
          <div class="btnWrap">
            <el-button size="small" :loading="exportLoading" type="primary"
                       v-if="permission.includes('sys:plan:export')" @click="exportAll">导出全部
            </el-button>
          </div>
        </template>
        <!--工单编号-->
        <template slot="number" slot-scope="{row}">
          <span style="cursor: pointer;color: var(--color-primary)"
                @click="$router.push('/inspection/plan/info?id=' + row.id)">
            {{ row.number }}
          </span>
        </template>
        <template slot="action" slot-scope="{row}">
          <el-link slot="reference" :underline="false" :disabled="!row.btn_start" @click="startPlan(row.id)"
                   type="primary">
            开始
          </el-link>
          <el-link slot="reference" :underline="false" :disabled="!row.btn_pause" @click="pausePlan(row.id)"
                   type="primary">
            暂停
          </el-link>
          <el-popconfirm class="ele-action" title="确定要删除此计划吗？" :disabled="!row.btn_delete"
                         @confirm="delPlan(row.id)">
            <el-link v-show="permission.includes('sys:plan:delete')" slot="reference" :disabled="!row.btn_delete"
                     :underline="false"
                     type="primary">
              {{ row.id ? '删除' : '' }}
            </el-link>
          </el-popconfirm>
        </template>
      </ele-pro-table>
      <el-dialog :visible.sync="addVisible" title="添加计划" width="1000px">
        <editForm :addVisible="addVisible" ref="addForm" v-if="addVisible"></editForm>
        <span slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary" @click="savePlan">确 定</el-button>
  </span>
      </el-dialog>
    </el-card>

  </div>
</template>

<script>
import {mapGetters} from "vuex";
import editForm from "@/views/inspection/plan/compoments/editForm.vue";

export default {
  components:{editForm},
  computed: {
    ...mapGetters(["permission"])
  },
  data() {
    return {
      addVisible: false,
      exportFlag: false,
      exportLoading: false,
      title: "嘉盛环境工单表格",
      typeList: [],
      // 表格数据接口
      url: '/polling_plan',
      // 表格列配置
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          fixed: "left"
        },
        {
          slot: 'number',
          label: '计划编号',
          width: 200,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'name',
          label: '计划名称',
          width: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'polling_customer_name',
          label: '客户',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          prop: 'polling_customer_user_name',
          label: '联系人',
          align: 'center',
          showOverflowTooltip: true,
          width: 100
        },

        {
          prop: 'polling_customer_user_telephone',
          label: '电话',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        },
        {
          prop: 'polling_customer_address',
          label: '客户地址',
          showOverflowTooltip: true,
          minWidth: 280,
          align: 'center'
        },
        {
          prop: 'plan_start_at',
          label: '计划开始时间',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          prop: 'plan_end_at',
          label: '计划截止时间',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          prop: 'polling_user_name',
          label: '负责人',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'create_user_name',
          label: '创建人',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'circle_unit_text',
          label: '重复周期',
          minWidth: 100,
          align: 'center',
        },
        {
          prop: 'status_text',
          label: '计划状态',
          minWidth: 160,
          align: 'center',
        },
        {
          prop: 'create_time',
          label: '创建时间',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',

        },
        {
          columnKey: 'action',
          label: '操作',
          width: 160,
          align: 'center',
          resizable: false,
          slot: 'action',
          fixed: "right"
        }
      ],
      loading: false,
      //显示新增联系人
      showCustomerUserEdit: false,
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      //当前编辑的类型
      type: '',
      // 当前编辑数据
      current: '',
      // 是否显示编辑弹窗
      showEdit: false,
      // 二维码是否显示编辑弹窗
      codeEdit: false,
      // 当前编辑数据
      currentCode: '',
      // 是否显示导入弹窗
      showImport: false,
      //客户id
      customer_id: '',
      //客户名字
      customer_name: '',
      statusList: [],
      //状态搜索激活
      activeNum: '',
      date: [],
    };
  },
  watch: {},
  mounted() {
    this.$http.get(`/polling_plan/params`,).then((res) => {
      this.statusList = res.data.data.status
    }).then((res) => {
      if (this.$route.query.status) {
        this.activeNum = res.findIndex((item) => item === this.$route.query.status)
        this.where.status = this.$route.query.status
        this.reload()
      }
    })
  },
  methods: {
    cancel() {
      this.addVisible = false
    },
    addPlan(){
      this.addVisible=true
    },
    savePlan() {
      if(this.$refs.addForm.onSubmit()){
        this.$http.post(`/polling_plan`,this.$refs.addForm.form).then((res) => {
          this.loading = true
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.addVisible = false
          } else {
            this.$message.error(res.data.msg);
          }
          this.loading = true
          this.reload()
        })
      }
    },
    delPlan(id) {
      this.$http.delete(`/polling_plan/${id}`,).then((res) => {
        this.loading = true
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
        this.loading = true
        this.reload()
      })
    },
    startPlan(id) {
      this.$http.post(`/polling_plan/${id}/start`,).then((res) => {
        this.loading = true
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
        this.loading = true
        this.reload()
      })
    },
    pausePlan(id) {
      this.$http.post(`/polling_plan/${id} /pause`,).then((res) => {
        this.loading = true
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
        this.loading = true
        this.reload()
      })
    },
    startDownload() {
      if (this.selection.length === 0)
        return false
      this.exportFlag = true
    },
    finishDownload() {
      this.exportFlag = false
    },
    /*导出全部*/
    exportAll() {
      this.exportLoading = true
      this.$http.get(`/polling_plan?export=1`, {params: this.where}).then((res) => {
        this.exportLoading = false
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          const link = document.createElement('a')
          //_blank表示在新窗口打开链接
          // link.target = '_blank'
          link.href = res.data.data
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    exportPart() {
      this.exportLoading = true
      this.$http.get(`/polling_plan?export=1`, {
        params: {
          ids: this.selection.map((item) => {
            return item.id
          }).join(',')
        }
      }).then((res) => {
        this.exportLoading = false
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          const link = document.createElement('a')
          //_blank表示在新窗口打开链接
          // link.target = '_blank'
          link.href = res.data.data
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    //筛选全部
    selectAll(flag) {
      switch (flag) {
        case 'activeNum':
          this.activeNum = ''
          this.where.status = ''
          break;
      }
      this.reload()
    },
    handelDateSearch(date) {
      this.where.date = date
      this.reload()
    },
    searchByStatusVersion(item, index) {
      this.activeNum = index
      this.where.status = item
      this.reload()
    },

    formSynergistic_people(row) {
      return ((row.users.filter((item) => {
        return item.is_master === 0
      })).map(item => {
        return item.user.realname
      })).join(' ')
    },
    handleCommand(command) {
      this.$router.push({path: '/workTickets/workTickets/addWorkTicket', query: {type: command}})
    },
    /* 刷新表格 */
    reload() {
      if (this.date?.length >= 0) {
        this.where.date_start = this.date[0]
        this.where.date_end = this.date[1]
      }
      this.$refs.table.reload({where: this.where});

    },
    /* 重置搜索 */
    reset() {
      this.activeNum = ''
      this.where = {};
      this.date = []
      this.reload();
    },
  }
}
</script>

<style scoped lang="scss">
.tableTop {
  display: flex;
  justify-content: space-between;
}

.searchWrap {
}

.active {
  background: #dcf3fd;
  border-color: #d0f3f4;
  color: #02aef3 !important;
  padding: 4px 8px;
}

.searchBox {
  display: flex;

  span {
    color: #a7b5b5;
    display: block;
    width: 110px;
    height: 36px;
    font-size: 16px;
  }

  .searchItem {
    border: 1px solid transparent;
    border-radius: 4px;
    color: gray;
    font-size: 13px;
    margin: 0 12px 8px 0;
    max-width: 160px;
    overflow: hidden;
    padding: 4px 8px;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    font-size: 14px;
  }
}

.el-autocomplete {
  width: 100%;

}

.el-input {
  width: 100% !important;
}

.btnWrap {
  display: flex;

  .el-button {
    margin-right: 10px;
  }
}
</style>
